package service

import (
	"global/structs"
	"global/function"
	"encoding/json"
	"github.com/garyburd/redigo/redis"
	"github.com/ngaut/log"
	"github.com/shopspring/decimal"
)

// 返回给客户端的数据
type OrderCoin struct {
	Price 			decimal.Decimal		`json:"price"`
	Number 			decimal.Decimal		`json:"number"`
	Flag 			string 				`json:"flag"`
	CreateTime 		string 				`json:"create_time"`
	Timestamp 		int64 				`json:"timestamp"`
}

func GetHistoryOrders(conn redis.Conn, pair string, floatNumber, floatPrice int) []structs.Order {
	orders := make([]structs.Order, 0)
	results := make([]OrderCoin, 0)
	datas, err := redis.Strings(conn.Do("LRANGE", function.GetOrderKey(pair), 0, 39))
	if err != nil {
		log.Errorf("get orders error, msg: %s", err.Error())
		return orders
	}

	for _, d := range datas {
		res, err := decodeOrder(d)
		if err != nil {
			log.Errorf("decode order data error, msg: %s", err.Error())
			continue
		}
		results = append(results, res)
	}

	for _, v := range results {
		orders = append(orders, structs.Order{
			Price: 		v.Price.StringFixedBank(int32(floatPrice)),
			Number: 	v.Number.StringFixedBank(int32(floatNumber)),
			Flag: 		v.Flag,
			CreateTime: v.CreateTime,
			Timestamp: 	v.Timestamp,
		})
	}

	return orders
}

func decodeOrder(str string) (OrderCoin, error) {
	var order OrderCoin
	err := json.Unmarshal([]byte(str), &order)
	return order, err
}